package dao;

import entity.College;
import entity.Major;
import util.DBUtil;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

//定义专业对象的数据库操作类
public class MajorDao {

    public int add(Major obj){
      String sql="insert into tb_major(name,college_id)"
              +"values("+obj.getName()+","+obj.getCollege_id()+")";
      return DBUtil.update(sql);
    }


    //2.定义查询的方法
    public List<Major> getAll(){
        List<Major> list  = new ArrayList<>();
        //从数据库的tb_major表中查询所有记录
        //遍历每条记录，生成一个Major对象
        //返回Major对象数组
        try {
            String sql = "select * from tb_major";
            ResultSet rs = DBUtil.query(sql);
            while (rs.next()) {
                Major  obj  = new Major(); //创建Major对象
                obj.setId(rs.getInt("id")); //属性赋值
                obj.setName(rs.getString("name"));
                obj.setCollege_id(rs.getInt("college_id"));
                list.add(obj); //加入到数组中
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return list;
    }

    //定义根据id获得特定数据的方法
    public Major  getById(Integer id){
        Major  obj = null;
        String sql = "select * from tb_major where id="+id;
        try{
            ResultSet rs = DBUtil.query(sql);
            if (rs.next()) {
                obj  = new Major();
                obj.setId(rs.getInt("id")); //属性赋值
                obj.setName(rs.getString("name"));
                obj.setCollege_id(rs.getInt("college_id"));
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return obj;
    }

    //定义修改方法
    public int  update(Major obj){
        String sql="update tb_major "
                 +" set name='"+obj.getName()+"' "
                 +", college_id='"+obj.getCollege_id()+"' "
                 +"  where  id= " +obj.getId();
        return DBUtil.update(sql);
    }

}
